import 'dart:core';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:dio/adapter.dart';
import 'package:flutter/foundation.dart';
import 'base_entity.dart';
import 'http_config.dart';
import 'http_entity.dart';
import 'http_executor.dart';
import 'package:short_video_app/utils/hud_util.dart';
import 'package:short_video_app/utils/sharepreferences_util.dart';
import 'package:short_video_app/other/user_manager.dart';

class HttpManager {
  Dio? _dio;
  String? token;
  HttpExecutor? _resultExecutor;

  /// 返回 Dio 基础配置
  static BaseOptions _setupBaseOptions() {
    /// 请求头
    Map<String, dynamic> headers = {};
    headers["Accept"] = "application/json";
    headers["OS"] = Platform.isAndroid ? "Android" : "IOS";
    headers["timestamp"] = DateTime.now().millisecondsSinceEpoch;
    headers["sign"] = "sign";
    headers["appVersion"] = "1.0.0";
    headers["groupcode"] = "JDY2207213624";
    // headers["deviceId"] = "deviceId";
    // headers["deviceName"] = "deviceName";
    // headers["appMarket"] = "appMarket";
    // headers["systemVersion"] = "1.0.0";
    // headers["appKey"] = "appKey";
    // headers["appID"] = "appID";

    BaseOptions baseOptions = BaseOptions(
      baseUrl: HttpConfig.baseURL,
      connectTimeout: HttpConfig.connectTimeout,
      receiveTimeout: HttpConfig.receiveTimeout,
      sendTimeout: HttpConfig.sendTimeout,
      headers: headers,
    );
    return baseOptions;
  }

  /// 工厂构造函数，用于实现单例模式
  factory HttpManager() => _instance;

  /// 初始化 HttpManager 实例
  static final HttpManager _instance = HttpManager._internal();
  HttpManager._internal() {
    if (_dio == null) {
      _dio = Dio(_setupBaseOptions());
      _resultExecutor = HttpExecutor();
    }
  }

  /// 获取 HttpManager 实例
  /// [baseURL], 可选参数，自定义请求基地址
  static HttpManager getInstance({String? baseURL}) {
    if (baseURL != null) {
      return _instance._customUrl(baseURL);
    }
    return _instance._normal();
  }

  /// 默认域名
  HttpManager _normal() {
    /// 设置请求基地址
    if (_dio?.options.baseUrl != HttpConfig.baseURL) {
      _dio?.options.baseUrl = HttpConfig.baseURL;
    }
    /// 设置代理
    // if (kDebugMode) {
    //   (_dio!.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
    //     client.findProxy = (uri) {
    //       return "PROXY 192.168.2.129:8888";
    //     };
    //   };
    // }
    return this;
  }

  /// 自定义域名
  HttpManager _customUrl(String baseURL) {
    _dio?.options.baseUrl = baseURL;
    return this;
  }

  /// 上传图片
  Future<IBaseEntity> uploadPic(String path, Map<String, dynamic> map) async {
    try {
      Response response = await _dio!.post(path, data: FormData.fromMap(map));
      return HttpEntity(status: true, errorDesc: "上传成功", data: '$path/${map['key']}');
    } catch (e) {
      return HttpEntity(status: false, errorDesc: "上传失败", data: '');
    }
  }

  /// 上传文件
  Future<IBaseEntity> uploadFile(String filePath, {required String name, required String businessCode}) async {
    try {
      Options op = Options();
      op.headers = {
        "Accept": "application/json",
        "Content-Type": "multipart/form-data",
      };
      Response response = await _dio!.post(
        HttpConfig.uploadFile,
        data: MultipartFile.fromFile(
          filePath,
          filename: name,
        ),
        queryParameters: {"businessCode": businessCode},
        options: op,
        onSendProgress: (count, total) {
          debugPrint((count / total).toString());
        },
      );
      return _resultExecutor!.onResponse(response: response);
    } catch (e) {
      return HttpEntity(status: false, errorDesc: "上传失败", data: '');
    }
  }

  /// 接口请求
  /// [url] 请求 API 路径
  /// [method] 请求方式
  /// [params] 自定义请求数据, GET 中为 Query Params, POST 中为 Body
  /// [header] 自定义请求头
  /// [formData] 请求数据是否需要使用 multipart/form-data 编码
  Future<IBaseEntity?> request<T>({
    required String url,
    Method method = Method.post,
    Map<String, dynamic>? params,
    Map<String, dynamic>? header,
    bool formData = false
  }) async {
    return _requestAsync(url, method: method, params: params, formData: formData);
  }

  Future<IBaseEntity?> _requestAsync<T>(String url, {
    Method method = Method.post,
    Map<String, dynamic>? params,
    Map<String, dynamic>? header,
    bool? formData
  }) async {
    /// 设置自定义的请求头
    if (header != null) {
      _dio?.options.headers = header;
    }
    /// 设置 token
    token = await UserManager().getToken();
    _dio?.options.headers["token"] = token;
    /// 设置默认值
    params = params ?? <String, dynamic>{};
    /// 进行请求
    try {
      Response? response;
      switch (method) {
        case Method.get:
          response = await _dio?.get(url, queryParameters: params);
          break;
        case Method.post:
          if (formData == true) {
            response = await _dio?.post(url, data: FormData.fromMap(params), onSendProgress: (count, total) { });
          } else {
            response = await _dio?.post(url, data: params);
          }
          break;
      }
      final data = response?.data;
      final errorCode = data["errorCode"] ?? 0;
      if (errorCode != 0) {
        HudUtil.toast(data["errorDesc"]);
      }
      return _resultExecutor?.onResponse(response: response);
    } on DioError catch (e) {
      /// 处理请求出错
      return _resultExecutor!.onError(exception: e);
    }
  }
}
